// 云函数入口文件

const cloud = require('wx-server-sdk')
const PDFDocument = require('pdfkit')

cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV }) // 使用当前云环境

const db = cloud.database()

async function fetchContract(contractId){
  const contractRes = await db.collection('contract').where({
    _id: contractId
  }).get()

  if(contractRes.data.length === 0){
    return null
  }

  return contractRes.data[0]
}



// 云函数入口函数

exports.main = async (event, context) => {

  const apiType = event.apiType

  const wxContext = cloud.getWXContext()

  let res = {code:0,msg:'',data:null}

  switch(apiType){



    case 'addContract':

      // 验证房间ID

      let roomId = event.roomId

      if(!roomId){

        res = {

          code:0,

          msg:'房间ID不能为空',

          data:null

        }

        break

      }

      // 从房间表获取房间信息

      const roomResult = await db.collection('room').where({

        _id: roomId,

        _openId: wxContext.OPENID

      }).get()

      if(roomResult.data.length === 0){

        res = {

          code:0,

          msg:'房间不存在或无权限',

          data:null

        }

        break

      }

      const roomInfo = roomResult.data[0]

      // 生成合同编号（16位字符串）

      let generatedContractNo = '';

      while(generatedContractNo.length < 16){

        generatedContractNo += Math.random().toString(36).slice(2);

      }

      generatedContractNo = generatedContractNo.slice(0, 16).toUpperCase();

      const newContractNo = event.contractNo || generatedContractNo;

      const contractData = {

        _openId: wxContext.OPENID, // 房东openId

        roomId: roomId, // 关联房间ID

        contractNo: newContractNo,

        status: 'pending', // 默认状态：待租客确认

        createTime: db.serverDate()

      }

      // ===== 房东发起合同时填写的信息 =====

      // 甲方（房东）信息
      if(event.landlordName) contractData.landlordName = event.landlordName
      if(event.landlordPhone) contractData.landlordPhone = event.landlordPhone
      if(event.landlordIdCard) contractData.landlordIdCard = event.landlordIdCard
      if(event.landlordAddress) contractData.landlordAddress = event.landlordAddress

      // 乙方（承租人）基本信息（房东填写，可选）
      if(event.tenantName) contractData.tenantName = event.tenantName
      if(event.tenantPhone) contractData.tenantPhone = event.tenantPhone
      if(event.tenantIdCard) contractData.tenantIdCard = event.tenantIdCard
      if(event.tenantAddress) contractData.tenantAddress = event.tenantAddress

      // 房屋信息（从房间表自动填充）

      if(roomInfo.province) contractData.province = roomInfo.province

      if(roomInfo.city) contractData.city = roomInfo.city

      if(roomInfo.district) contractData.district = roomInfo.district

      if(roomInfo.street) contractData.street = roomInfo.street

      if(roomInfo.address) contractData.address = roomInfo.address

      if(roomInfo.room) contractData.room = roomInfo.room // 房间号

      if(roomInfo.area) contractData.area = roomInfo.area // 面积

      // 户型信息
      if(roomInfo.roomType) contractData.roomType = roomInfo.roomType // 户型：一室一厅一卫、两室一厅一卫

      // 如果前端传递了roomType，优先使用前端的（允许覆盖）
      if(event.roomType) contractData.roomType = event.roomType

      // 物业费（从房间表自动填充）

      if(roomInfo.propertyFee) contractData.propertyFee = roomInfo.propertyFee

      // 租赁期限

      if(event.startYear) contractData.startYear = event.startYear

      if(event.startMonth) contractData.startMonth = event.startMonth

      if(event.startDay) contractData.startDay = event.startDay

      if(event.endYear) contractData.endYear = event.endYear

      if(event.endMonth) contractData.endMonth = event.endMonth

      if(event.endDay) contractData.endDay = event.endDay

      if(event.renewNoticeMonths) contractData.renewNoticeMonths = event.renewNoticeMonths

      // 租金信息

      if(event.monthlyRent) contractData.monthlyRent = event.monthlyRent

      if(event.monthlyRentUpper) contractData.monthlyRentUpper = event.monthlyRentUpper

      if(event.paymentMethod) contractData.paymentMethod = event.paymentMethod

      if(event.paymentDaysBefore) contractData.paymentDaysBefore = event.paymentDaysBefore

      if(event.lateFeePercent) contractData.lateFeePercent = event.lateFeePercent

      // 押金信息

      if(event.deposit) contractData.deposit = event.deposit

      if(event.depositUpper) contractData.depositUpper = event.depositUpper

      // 物业费

      if(event.propertyFee) contractData.propertyFee = event.propertyFee

      // 交付日期

      if(event.deliveryYear) contractData.deliveryYear = event.deliveryYear

      if(event.deliveryMonth) contractData.deliveryMonth = event.deliveryMonth

      if(event.deliveryDay) contractData.deliveryDay = event.deliveryDay

      // 合同解除相关

      if(event.overdueDays) contractData.overdueDays = event.overdueDays

      if(event.overdueAmount) contractData.overdueAmount = event.overdueAmount

      // 违约责任

      if(event.penaltyAmount) contractData.penaltyAmount = event.penaltyAmount

      if(event.penaltyAmountUpper) contractData.penaltyAmountUpper = event.penaltyAmountUpper

      // 物品清单

      if(event.goods && Array.isArray(event.goods)) contractData.goods = event.goods

      // ===== 租客确认合同时填写的信息（此时更新） =====

      // 租客详细信息

      if(event.tenantIdCard) contractData.tenantIdCard = event.tenantIdCard

      if(event.emergencyContact) contractData.emergencyContact = event.emergencyContact

      if(event.emergencyPhone) contractData.emergencyPhone = event.emergencyPhone

      // 租客签名图片

      if(event.tenantSignature) contractData.tenantSignature = event.tenantSignature

      // 如果租客已确认，更新状态

      if(event.status) contractData.status = event.status

      const addResult = await db.collection('contract').add({

        data: contractData

      })

      res = {

        code:200,

        msg:'添加合同成功',

        data:{

          _id: addResult._id,

          contractNo: newContractNo

        }

      }

    break



    case 'updateContractTenantDetails':

      if(!event.contractId){

        res = {

          code:0,

          msg:'合同ID不能为空',

          data:null

        }

        break

      }

      const tenantDetailsContract = await fetchContract(event.contractId)

      if(!tenantDetailsContract){

        res = {

          code:0,

          msg:'合同不存在',

          data:null

        }

        break

      }

      let tenantDetailsUpdate = {}

      const tenantDetailFields = ['tenantName','tenantPhone','startYear','startMonth','startDay','endYear','endMonth','endDay','monthlyRent','paymentMethod','deposit']

      tenantDetailFields.forEach(field => {
        if(event.hasOwnProperty(field)){
          tenantDetailsUpdate[field] = event[field]
        }
      })

      if(Object.keys(tenantDetailsUpdate).length === 0){

        res = {

          code:0,

          msg:'没有可更新的字段',

          data:null

        }

        break

      }

      tenantDetailsUpdate.updateTime = db.serverDate()

      await db.collection('contract').where({

        _id: event.contractId

      }).update({

        data: tenantDetailsUpdate

      })

      res = {

        code:200,

        msg:'更新承租人信息成功',

        data:{

          contractId: event.contractId

        }

      }

    break



    case 'updateContractTenantContact':

      if(!event.contractId){

        res = {

          code:0,

          msg:'合同ID不能为空',

          data:null

        }

        break

      }

      const tenantContactContract = await fetchContract(event.contractId)

      if(!tenantContactContract){

        res = {

          code:0,

          msg:'合同不存在',

          data:null

        }

        break

      }

      let tenantContactUpdate = {}

      const tenantContactFields = ['tenantName','tenantPhone','tenantIdCard','tenantAddress','emergencyContact','emergencyPhone']

      tenantContactFields.forEach(field => {
        if(event.hasOwnProperty(field)){
          tenantContactUpdate[field] = event[field]
        }
      })

      if(Object.keys(tenantContactUpdate).length === 0){

        res = {

          code:0,

          msg:'没有可更新的字段',

          data:null

        }

        break

      }

      tenantContactUpdate.updateTime = db.serverDate()

      await db.collection('contract').where({

        _id: event.contractId

      }).update({

        data: tenantContactUpdate

      })

      res = {

        code:200,

        msg:'更新合同联系信息成功',

        data:{

          contractId: event.contractId

        }

      }

    break



    case 'updateContractGoods':

      if(!event.contractId){

        res = {

          code:0,

          msg:'合同ID不能为空',

          data:null

        }

        break

      }

      if(!event.goods || !Array.isArray(event.goods)){

        res = {

          code:0,

          msg:'物品数据格式不正确',

          data:null

        }

        break

      }

      const goodsContract = await fetchContract(event.contractId)

      if(!goodsContract){

        res = {

          code:0,

          msg:'合同不存在',

          data:null

        }

        break

      }

      await db.collection('contract').where({

        _id: event.contractId

      }).update({

        data: {

          goods: event.goods,

          updateTime: db.serverDate()

        }

      })

      res = {

        code:200,

        msg:'更新合同物品成功',

        data:{

          contractId: event.contractId,

          goods: event.goods

        }

      }

    break



    case 'updateContractLandlordSignature':

      if(!event.contractId){

        res = {

          code:0,

          msg:'合同ID不能为空',

          data:null

        }

        break

      }

      if(!event.landlordSignature){

        res = {

          code:0,

          msg:'签名文件不能为空',

          data:null

        }

        break

      }

      const landlordSignatureContract = await fetchContract(event.contractId)

      if(!landlordSignatureContract){

        res = {

          code:0,

          msg:'合同不存在',

          data:null

        }

        break

      }

      await db.collection('contract').where({

        _id: event.contractId

      }).update({

        data: {

          landlordSignature: event.landlordSignature,

          updateTime: db.serverDate()

        }

      })

      res = {

        code:200,

        msg:'房东签名更新成功',

        data:{

          contractId: event.contractId,

          landlordSignature: event.landlordSignature

        }

      }

    break



    case 'updateContractTenantSignature':

      if(!event.contractId){

        res = {

          code:0,

          msg:'合同ID不能为空',

          data:null

        }

        break

      }

      if(!event.tenantSignature){

        res = {

          code:0,

          msg:'签名文件不能为空',

          data:null

        }

        break

      }

      const tenantSignatureContract = await fetchContract(event.contractId)

      if(!tenantSignatureContract){

        res = {

          code:0,

          msg:'合同不存在',

          data:null

        }

        break

      }

      let tenantSignatureUpdate = {

        updateTime: db.serverDate()

      }

      if(event.tenantSignature) tenantSignatureUpdate.tenantSignature = event.tenantSignature

      await db.collection('contract').where({

        _id: event.contractId

      }).update({

        data: tenantSignatureUpdate

      })

      res = {

        code:200,

        msg:'租客签名更新成功',

        data:{

          contractId: event.contractId,

          tenantSignature: event.tenantSignature

        }

      }

    break



    case 'markContractCreated':

      if(!event.contractId){

        res = {

          code:0,

          msg:'合同ID不能为空',

          data:null

        }

        break

      }

      const createdContract = await fetchContract(event.contractId)

      if(!createdContract){

        res = {

          code:0,

          msg:'合同不存在',

          data:null

        }

        break

      }

      let creationStatus = 'pending'
      if(event.status) creationStatus = event.status

      await db.collection('contract').where({

        _id: event.contractId

      }).update({

        data: {

          status: creationStatus,

          updateTime: db.serverDate()

        }

      })

      res = {

        code:200,

        msg:'合同状态已更新',

        data:{

          contractId: event.contractId,

          status: creationStatus

        }

      }

    break



    case 'completeContract':

      if(!event.contractId){

        res = {

          code:0,

          msg:'合同ID不能为空',

          data:null

        }

        break

      }

      const completeContractItem = await fetchContract(event.contractId)

      if(!completeContractItem){

        res = {

          code:0,

          msg:'合同不存在',

          data:null

        }

        break

      }

      let finalStatus = event.status || 'active'

      // 准备更新数据
      const updateData = {
        status: finalStatus,
        updateTime: db.serverDate()
      }

      // 如果传入了房间物品数据，保存到合同
      if(event.roomItems && Array.isArray(event.roomItems)){
        updateData.roomItems = event.roomItems
      } else if(completeContractItem.roomId) {
        // 如果没有传入物品数据，但有 roomId，则从房间表获取
        try {
          const roomResult = await db.collection('room').where({
            _id: completeContractItem.roomId
          }).get()
          
          if(roomResult.data.length > 0){
            const roomInfo = roomResult.data[0]
            if(roomInfo.items && Array.isArray(roomInfo.items)){
              updateData.roomItems = roomInfo.items
            }
          }
        } catch(error) {
          console.error('获取房间物品失败:', error)
        }
      }

      await db.collection('contract').where({

        _id: event.contractId

      }).update({

        data: updateData

      })

      res = {

        code:200,

        msg:'合同签约完成',

        data:{

          contractId: event.contractId,

          status: finalStatus

        }

      }

    break



    case 'getContractInfo':

      let getContractId = event.contractId

      let getContractNo = event.contractNo

      if(!getContractId && !getContractNo){

        res = {

          code:0,

          msg:'合同ID或合同编号不能为空',

          data:null

        }

        break

      }

      // 通过ID或编号查找合同

      let queryCondition = {}

      if(getContractId){

        queryCondition._id = getContractId

      } else if(getContractNo){

        queryCondition.contractNo = getContractNo

      }

      const contract = await db.collection('contract').where(queryCondition).get()

      if(contract.data.length === 0){

        res = {

          code:0,

          msg:'合同不存在',

          data:null

        }

        break

      }

      res = {

        code:200,

        msg:'获取合同信息成功',

        data:contract.data[0]

      }

    break



    case 'getContractList':

      const whereCondition = {}

      // 如果是房东，获取自己的合同列表

      whereCondition._openId = wxContext.OPENID

      // 如果是租客，根据tenantPhone查询（因为租客可能还没有openId，通过phone匹配）

      if(event.role === 'tenant' && event.phone){

        whereCondition.tenantPhone = event.phone

        delete whereCondition._openId

      }

      // 可选的状态筛选

      if(event.status){

        whereCondition.status = event.status

      }

      // 可选的房屋筛选

      if(event.roomId){

        whereCondition.roomId = event.roomId

      }

      const contractList = await db.collection('contract')

        .where(whereCondition)

        .orderBy('createTime', 'desc')

        .get()

      res = {

        code:200,

        msg:'获取合同列表成功',

        data:contractList.data

      }

    break



    case 'deleteContract':

      let deleteContractId = event.contractId

      if(!deleteContractId){

        res = {

          code:0,

          msg:'合同ID不能为空',

          data:null

        }

        break

      }

      // 先检查合同是否存在且属于当前用户

      const deleteCheck = await db.collection('contract').where({

        _id: deleteContractId,

        _openId: wxContext.OPENID

      }).get()

      if(deleteCheck.data.length === 0){

        res = {

          code:0,

          msg:'合同不存在或无权限',

          data:null

        }

        break

      }

      await db.collection('contract').where({

        _id: deleteContractId,

        _openId: wxContext.OPENID

      }).remove()

      res = {

        code:200,

        msg:'删除合同成功',

        data:{

          contractId: deleteContractId

        }

      }

    break



    case 'imageToPDF':

      if(!event.imageFileId){

        res = {

          code:0,

          msg:'图片文件ID不能为空',

          data:null

        }

        break

      }

      try {

        // 下载图片文件
        const imageFile = await cloud.downloadFile({
          fileID: event.imageFileId
        })

        // 读取图片buffer
        const imageBuffer = imageFile.fileContent

        // 创建PDF文档
        const doc = new PDFDocument({
          size: 'A4',
          margins: { top: 0, bottom: 0, left: 0, right: 0 }
        })

        // 将PDF转换为Buffer
        const chunks = []
        const pdfPromise = new Promise((resolve, reject) => {
          doc.on('data', chunk => chunks.push(chunk))
          doc.on('end', () => resolve(Buffer.concat(chunks)))
          doc.on('error', reject)
        })

        // 获取A4尺寸（595x842点，转换为像素约2480x3508）
        const a4Width = 595
        const a4Height = 842

        // 将图片添加到PDF（居中，保持比例）
        doc.image(imageBuffer, 0, 0, {
          width: a4Width,
          height: a4Height,
          fit: [a4Width, a4Height],
          align: 'center',
          valign: 'center'
        })

        // 结束PDF
        doc.end()

        // 等待PDF生成完成
        const pdfBuffer = await pdfPromise

        // 上传PDF到云存储
        const cloudPath = `contracts/contract-${Date.now()}.pdf`
        const uploadResult = await cloud.uploadFile({
          cloudPath: cloudPath,
          fileContent: pdfBuffer
        })

        res = {

          code:200,

          msg:'PDF生成成功',

          data:{

            fileId: uploadResult.fileID

          }

        }

      } catch(error) {

        console.error('图片转PDF失败:', error)

        res = {

          code:0,

          msg:'图片转PDF失败：' + error.message,

          data:null

        }

      }

    break



    case 'generateContractPDF':

      if(!event.contractId){

        res = {

          code:0,

          msg:'合同ID不能为空',

          data:null

        }

        break

      }

      const contractForPDF = await fetchContract(event.contractId)

      if(!contractForPDF){

        res = {

          code:0,

          msg:'合同不存在',

          data:null

        }

        break

      }

      try {

        // 创建PDF文档
        const doc = new PDFDocument({
          size: 'A4',
          margins: { top: 50, bottom: 50, left: 50, right: 50 }
        })

        // 将PDF转换为Buffer - 使用Promise包装
        const chunks = []
        const pdfPromise = new Promise((resolve, reject) => {
          doc.on('data', chunk => chunks.push(chunk))
          doc.on('end', () => resolve(Buffer.concat(chunks)))
          doc.on('error', reject)
        })

        // 设置字体（使用默认字体）
        const fontSize = 12
        const lineHeight = 18
        let yPosition = 50

        // 标题
        doc.fontSize(20).text('房屋租赁合同', { align: 'center' })
        yPosition += 40

        // 甲方信息
        doc.fontSize(fontSize)
        doc.text(`甲方（出租方/房东）：${contractForPDF.landlordName || '未填写'}`, 50, yPosition)
        yPosition += lineHeight
        doc.text(`联系电话：${contractForPDF.landlordPhone || '未填写'}`, 50, yPosition)
        yPosition += lineHeight
        doc.text(`身份证号：${contractForPDF.landlordIdCard || '未填写'}`, 50, yPosition)
        yPosition += lineHeight
        doc.text(`地址：${contractForPDF.landlordAddress || '未填写'}`, 50, yPosition)
        yPosition += lineHeight * 2

        // 乙方信息
        doc.text(`乙方（承租方/租客）：${contractForPDF.tenantName || '未填写'}`, 50, yPosition)
        yPosition += lineHeight
        doc.text(`联系电话：${contractForPDF.tenantPhone || '未填写'}`, 50, yPosition)
        yPosition += lineHeight
        doc.text(`身份证号：${contractForPDF.tenantIdCard || '未填写'}`, 50, yPosition)
        yPosition += lineHeight
        doc.text(`地址：${contractForPDF.tenantAddress || '未填写'}`, 50, yPosition)
        yPosition += lineHeight * 2

        // 合同内容
        doc.text('根据《中华人民共和国民法典》及相关法律法规的规定，甲乙双方在平等、自愿、公平、诚实信用的基础上，就乙方租赁甲方房屋事宜达成如下协议：', 50, yPosition, { width: 500 })
        yPosition += lineHeight * 2

        // 一、租赁房屋详情
        doc.fontSize(14).text('一、租赁房屋详情', 50, yPosition)
        yPosition += lineHeight
        doc.fontSize(fontSize)
        const address = `${contractForPDF.province || ''}${contractForPDF.city || ''}${contractForPDF.district || ''}${contractForPDF.street || ''}${contractForPDF.address || ''}${contractForPDF.room || ''}室`
        doc.text(`1.甲方将位于${address}的房屋出租给乙方使用。该房屋的建筑面积为${contractForPDF.area || '未填写'}平方米，户型为${contractForPDF.roomType || '未设置'}。`, 50, yPosition, { width: 500 })
        yPosition += lineHeight * 2

        // 二、租赁期限约定
        doc.fontSize(14).text('二、租赁期限约定', 50, yPosition)
        yPosition += lineHeight
        doc.fontSize(fontSize)
        const startDate = `${contractForPDF.startYear || ''}年${contractForPDF.startMonth || ''}月${contractForPDF.startDay || ''}日`
        let endDateText = ''
        if(contractForPDF.endYear && contractForPDF.endMonth && contractForPDF.endDay) {
          endDateText = `至${contractForPDF.endYear}年${contractForPDF.endMonth}月${contractForPDF.endDay}日止`
        } else {
          endDateText = '，具体期限另行约定'
        }
        doc.text(`1.租赁期限自${startDate}起${endDateText}。`, 50, yPosition, { width: 500 })
        yPosition += lineHeight
        doc.text(`2.租赁期满，甲方有权收回房屋，乙方应如期归还。乙方如需续租，应在租赁期满前${contractForPDF.renewNoticeMonths || ''}个月书面通知甲方，并经甲方同意后重新签订租赁合同。`, 50, yPosition, { width: 500 })
        yPosition += lineHeight * 2

        // 三、租金及支付方式
        doc.fontSize(14).text('三、租金及支付方式', 50, yPosition)
        yPosition += lineHeight
        doc.fontSize(fontSize)
        doc.text(`1.租金金额为每月人民币${contractForPDF.monthlyRent || ''}元（大写${contractForPDF.monthlyRentUpper || ''}）。`, 50, yPosition, { width: 500 })
        yPosition += lineHeight
        doc.text(`2.租金支付方式为${contractForPDF.paymentMethod || ''}。乙方应在每个支付周期开始前${contractForPDF.paymentDaysBefore || ''}日内向甲方支付租金。`, 50, yPosition, { width: 500 })
        yPosition += lineHeight
        doc.text(`3.乙方逾期支付租金的，每逾期一日，应按当月租金的${contractForPDF.lateFeePercent || ''}%向甲方支付违约金。`, 50, yPosition, { width: 500 })
        yPosition += lineHeight * 2

        // 四、押金
        doc.fontSize(14).text('四、押金', 50, yPosition)
        yPosition += lineHeight
        doc.fontSize(fontSize)
        doc.text(`1.乙方应在签订本合同的同时向甲方支付人民币${contractForPDF.deposit || ''}元（大写${contractForPDF.depositUpper || ''}）作为押金。租赁期满或合同终止后，甲方应将押金无息退还给乙方。`, 50, yPosition, { width: 500 })
        yPosition += lineHeight * 2

        // 五、房屋交付及使用规定
        doc.fontSize(14).text('五、房屋交付及使用规定', 50, yPosition)
        yPosition += lineHeight
        doc.fontSize(fontSize)
        const deliveryDate = `${contractForPDF.deliveryYear || ''}年${contractForPDF.deliveryMonth || ''}月${contractForPDF.deliveryDay || ''}日`
        doc.text(`1.甲方应于${deliveryDate}将房屋交付给乙方，并确保房屋及附属设施设备完好。`, 50, yPosition, { width: 500 })
        yPosition += lineHeight * 2

        // 八、合同的解除
        doc.fontSize(14).text('八、合同的解除', 50, yPosition)
        yPosition += lineHeight
        doc.fontSize(fontSize)
        doc.text(`3.乙方未按照约定支付租金达${contractForPDF.overdueDays || ''}日以上，或者欠缴各项费用达人民币${contractForPDF.overdueAmount || ''}元以上的，甲方有权解除合同，并要求乙方赔偿损失。`, 50, yPosition, { width: 500 })
        yPosition += lineHeight * 2

        // 十二、其他条款
        doc.fontSize(14).text('十二、其他条款', 50, yPosition)
        yPosition += lineHeight
        doc.fontSize(fontSize)
        doc.text('3.本合同自甲乙双方签字之日起生效。', 50, yPosition, { width: 500 })
        yPosition += lineHeight * 2

        // 签名区域
        if(contractForPDF.landlordSignature) {
          doc.fontSize(14).text('房东签字和日期', 50, yPosition)
          yPosition += lineHeight
          // 注意：这里可以添加签名图片，但需要先下载图片
          doc.text('（已签名）', 50, yPosition)
          yPosition += lineHeight * 2
        }

        if(contractForPDF.tenantSignature) {
          doc.fontSize(14).text('租客签字和日期', 50, yPosition)
          yPosition += lineHeight
          doc.text('（已签名）', 50, yPosition)
        }

        // 结束PDF
        doc.end()

        // 等待PDF生成完成
        const pdfBuffer = await pdfPromise

        // 上传PDF到云存储
        const cloudPath = `contracts/contract-${event.contractId}-${Date.now()}.pdf`
        const uploadResult = await cloud.uploadFile({
          cloudPath: cloudPath,
          fileContent: pdfBuffer
        })

        res = {

          code:200,

          msg:'PDF生成成功',

          data:{

            fileId: uploadResult.fileID

          }

        }

      } catch(error) {

        console.error('生成PDF失败:', error)

        res = {

          code:0,

          msg:'生成PDF失败：' + error.message,

          data:null

        }

      }

    break



    default:

      res = {

        code:0,

        msg:'没有对应的接口',

        data:null

      }

  }



  return {

    res

  }

}
